package com.umsoft.smart.framework.helper;

import com.umsoft.smart.framework.Bean.Handler;
import com.umsoft.smart.framework.Bean.Request;
import com.umsoft.smart.framework.annotation.Action;
import com.umsoft.smart.framework.util.CollectionUtil;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 控制器助手类
 */
public final class ControllerHelper {

    private static final Map<Request,Handler> ACTION_MAP = new HashMap<>();

    static {
        Set<Class<?>> controllerClassSet = ClassHelper.getControllerClassSet();
        if(CollectionUtil.isNotEmpty(controllerClassSet)){
            controllerClassSet.stream().forEach(cls->{
                Method[] methods = cls.getMethods();
                if(ArrayUtils.isNotEmpty(methods)){
                    for (Method method : methods){
                        if(method.isAnnotationPresent(Action.class)){
                            //获取 URL 映射规则
                            Action action = method.getAnnotation(Action.class);
                            String mapping = action.value();
                            //验证 URL 规则
                            if(mapping.matches("\\w+:/\\w*")){
                                String[] array = mapping.split(":");
                                //获取请求方法和路径
                                String requestMethod = array[0];
                                String requestPath = array[1];
                                Request request = new Request(requestMethod,requestPath);
                                Handler handler = new Handler(cls,method);
                                //初始化 Action_MAP
                                ACTION_MAP.put(request,handler);
                            }
                        }
                    }
                }
            });
        }
    }

    /**
     * 获取 Handler
     * @param requestMethod
     * @param requestPath
     * @return
     */
    public static Handler getHandler(String requestMethod,String requestPath){
        Request request = new Request(requestMethod,requestPath);
        return ACTION_MAP.get(request);
    }
}
